/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package com.inspur.edp.metadata.rtcustomization.core;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.inspur.edp.lcm.metadata.api.entity.GspMetadata;
import com.inspur.edp.lcm.metadata.api.entity.MetadataDto;
import com.inspur.edp.lcm.metadata.api.entity.MetadataReference;
import com.inspur.edp.lcm.metadata.common.MetadataSerializer;
import com.inspur.edp.lcm.metadata.common.ServiceUtils;
import com.inspur.edp.lcm.metadata.common.configuration.MetadataServiceHelper;
import com.inspur.edp.metadata.rtcustomization.api.CustomizationService;
import com.inspur.edp.metadata.rtcustomization.api.MimicService;
import com.inspur.edp.metadata.rtcustomization.api.entity.AppTemplate;
import com.inspur.edp.metadata.rtcustomization.api.entity.AppTemplateDto;
import com.inspur.edp.metadata.rtcustomization.api.entity.ConfigData;
import com.inspur.edp.metadata.rtcustomization.api.entity.MetadataQueryParam;
import com.inspur.edp.metadata.rtcustomization.api.entity.MetadataScopeEnum;
import com.inspur.edp.metadata.rtcustomization.api.entity.MimicParamKeyEnum;
import com.inspur.edp.metadata.rtcustomization.api.entity.MimicTypeEnum;
import com.inspur.edp.metadata.rtcustomization.api.entity.config.ConfigDataConfiguration;
import com.inspur.edp.metadata.rtcustomization.common.Constants;
import com.inspur.edp.metadata.rtcustomization.common.CustomizationConfigLoader;
import com.inspur.edp.metadata.rtcustomization.common.ExtractConfigDataHelper;
import com.inspur.edp.metadata.rtcustomization.common.MetadataCopyHelper;
import com.inspur.edp.metadata.rtcustomization.common.ReferenceHelper;
import com.inspur.edp.metadata.rtcustomization.common.event.MimicServiceEventBroker;
import com.inspur.edp.metadata.rtcustomization.context.MimicServiceContext;
import com.inspur.edp.metadata.rtcustomization.context.MimicServiceContextHolder;
import com.inspur.edp.metadata.rtcustomization.spi.ConfigDataCollectSpi;
import com.inspur.edp.metadata.rtcustomization.spi.ConfigDataCopySpi;
import com.inspur.edp.metadata.rtcustomization.spi.ExtractConfigDataSpi;
import com.inspur.edp.metadata.rtcustomization.spi.IMetadataRtReferenceManager;
import com.inspur.edp.metadata.rtcustomization.spi.MetadataCollectSpi;
import com.inspur.edp.metadata.rtcustomization.spi.MetadataCopySpi;
import com.inspur.edp.metadata.rtcustomization.spi.event.MimicServiceEventArgs;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

/**
 * 复制服务实现类
 */
@Slf4j
public class MimicServiceImpl implements MimicService {
    private static final String CONFIG_DATA_PRE_CONFIGURATION = "ConfigDataPreConfiguration";
    private static final String CONFIG_DATA_POST_CONFIGURATION = "ConfigDataPostConfiguration";
    private CustomizationService customizationService;
    private MimicSaveService mimicSaveService;

    @Override
    public AppTemplateDto generateTemplate(MimicTypeEnum mimicTypeEnum, Map<MimicParamKeyEnum, String> paramMap) {
        // 参数校验
        paramCheck(mimicTypeEnum);

        // 收集元数据
        List<GspMetadata> gspMetadataList = getMetadataList(mimicTypeEnum, paramMap);
        // 提取元数据中配置依赖项
        extractConfigData(gspMetadataList);
        // 配置数据
        List<ConfigData> configDataList = getConfigDataList(mimicTypeEnum, paramMap);

        // 构造返回数据
        AppTemplateDto appTemplateDto = convertToAppTemplateDto(mimicTypeEnum, gspMetadataList, configDataList);
        appTemplateDto.setParamMap(paramMap);
        return appTemplateDto;
    }

    @Override
    public void mimicByTemplate(MimicTypeEnum mimicTypeEnum, Map<MimicParamKeyEnum, String> paramMap,
        AppTemplateDto appTemplateDto) {
        try {
            // 参数校验
            paramCheck(mimicTypeEnum, appTemplateDto);
            mimicContextProcess();

            // 合并参数
            paramMap = mergeMimicParam(paramMap,appTemplateDto.getParamMap());
            // 解析模板数据
            AppTemplate appTemplate = convertToAppTemplate(appTemplateDto);

            // 生成新的元数据id
            generateMdId(appTemplate.getGspMetadataList());
            // 复制元数据、配置数据
            List<ConfigData> configDataPreList = getPreConfigData(appTemplate.getConfigDataList());
            List<ConfigData> configDataPostList = getPostConfigData(appTemplate.getConfigDataList());
            configDataCopy(mimicTypeEnum, paramMap, configDataPreList);
            List<GspMetadata> gspMetadataList = metadataCopy(paramMap, appTemplate.getGspMetadataList());
            configDataCopy(mimicTypeEnum, paramMap, configDataPostList);
            List<ConfigData> configDataCopyList = new ArrayList<>();
            if (!CollectionUtils.isEmpty(configDataPreList)) {
                configDataCopyList.addAll(configDataPreList);
            }
            if (!CollectionUtils.isEmpty(configDataPostList)) {
                configDataCopyList.addAll(configDataPostList);
            }
            getMimicSaveService().mimicSave(mimicTypeEnum, gspMetadataList, configDataCopyList);
        } finally {
            MimicServiceContextHolder.purge();
        }
    }

    private Map<MimicParamKeyEnum, String> mergeMimicParam(Map<MimicParamKeyEnum, String> srcParam, Map<MimicParamKeyEnum, String> resParam) {

        if (srcParam != null && !CollectionUtils.isEmpty(resParam)) {
            resParam.forEach((key, value) -> {
                if (!StringUtils.hasText(srcParam.get(key))) {
                    srcParam.put(key, value);
                }
            });
            return srcParam;
        }

        return srcParam == null ? resParam : srcParam;
    }

    @Override public void mimic(MimicTypeEnum mimicTypeEnum, Map<MimicParamKeyEnum, String> paramMap) {
        try {
            // 参数校验
            paramCheck(mimicTypeEnum);
            mimicContextProcess();

            // 收集元数据
            List<GspMetadata> gspMetadataList = getMetadataList(mimicTypeEnum, paramMap);
            // 提取元数据中配置依赖项
            extractConfigData(gspMetadataList);
            // 收集配置数据
            List<ConfigData> configDataList = getConfigDataList(mimicTypeEnum, paramMap);
            // 复制一份待处理元数据及配置数据
            AppTemplate appTemplate = convertToAppTemplate(convertToAppTemplateDto(mimicTypeEnum, gspMetadataList, configDataList));
            gspMetadataList = appTemplate.getGspMetadataList();
            configDataList = appTemplate.getConfigDataList();

            // 元数据id处理
            generateMdId(gspMetadataList);
            // 复制元数据、配置数据
            List<ConfigData> configDataPreList = getPreConfigData(configDataList);
            List<ConfigData> configDataPostList = getPostConfigData(configDataList);
            configDataCopy(mimicTypeEnum, paramMap, configDataPreList);
            List<GspMetadata> gspMetadataListAfterCopy = metadataCopy(paramMap, gspMetadataList);
            configDataCopy(mimicTypeEnum, paramMap, configDataPostList);
            List<ConfigData> configDataCopyList = new ArrayList<>();
            if (!CollectionUtils.isEmpty(configDataPreList)) {
                configDataCopyList.addAll(configDataPreList);
            }
            if (!CollectionUtils.isEmpty(configDataPostList)) {
                configDataCopyList.addAll(configDataPostList);
            }
            getMimicSaveService().mimicSave(mimicTypeEnum, gspMetadataListAfterCopy, configDataCopyList);
        } finally {
            MimicServiceContextHolder.purge();
        }
    }

    /**
     * 初始上下文
     */
    private void mimicContextProcess() {
        MimicServiceContextHolder.setCurrentContext(MimicServiceContext.ofMimicServiceContext());
    }

    /**
     * 参数校验
     *
     * @param mimicTypeEnum
     */
    private void paramCheck(MimicTypeEnum mimicTypeEnum) {
        Assert.notNull(mimicTypeEnum, "参数错误, 复制类型不能为空");
    }

    /**
     * 参数校验
     *
     * @param mimicTypeEnum
     * @param appTemplateDto
     */
    private void paramCheck(MimicTypeEnum mimicTypeEnum, AppTemplateDto appTemplateDto) {
        paramCheck(mimicTypeEnum);
        Assert.notNull(appTemplateDto, "参数错误, 模板数据不能为空");
        Assert.notNull(appTemplateDto.getMimicType(), "参数错误, 模板数据不能为空");
        if (mimicTypeEnum.getCode() != appTemplateDto.getMimicType()) {
            throw new RuntimeException("当前模板格式不支持，请选择正确的模板文件");
        }
    }

    /**
     * 收集元数据
     *
     * @param mimicTypeEnum
     * @param paramMap
     * @return
     */
    private List<GspMetadata> getMetadataList(MimicTypeEnum mimicTypeEnum, Map<MimicParamKeyEnum, String> paramMap) {
        List<GspMetadata> gspMetadataList = new ArrayList<>();
        List<MetadataCollectSpi> metadataCollectSpiList = MimicSpiServiceFactory.getSpiService(mimicTypeEnum, MetadataCollectSpi.class);
        for (MetadataCollectSpi metadataCollectSpi : metadataCollectSpiList) {
            List<MetadataDto> metadataDtoList = metadataCollectSpi.metadataCollect(paramMap);
            if (CollectionUtils.isEmpty(metadataDtoList)) {
                continue;
            }
            for (MetadataDto metadataDto : metadataDtoList) {
                MetadataQueryParam metadataQueryParam = new MetadataQueryParam();
                metadataQueryParam.setMetadataId(metadataDto.getId());
                metadataQueryParam.setMetadataScopeEnum(MetadataScopeEnum.CUSTOMIZING);
                GspMetadata gspMetadata = getCustomizationService().getGspMetadata(metadataQueryParam);
                Assert.notNull(gspMetadata, "找不到元数据, " + metadataDto.getId() + ":" + metadataDto.getCode() + ":" + metadataDto.getName());
                gspMetadataList.add(gspMetadata);
            }
        }
        // 元数据列表去重检查
        if (!CollectionUtils.isEmpty(gspMetadataList)) {
            Set<String> mdIdSet = gspMetadataList.stream().map(gspMetadata1 -> gspMetadata1.getHeader().getId()).collect(Collectors.toSet());
            Assert.isTrue(mdIdSet.size() == gspMetadataList.size(), "收集的元数据列表数据不允许重复");
        }
        return gspMetadataList;
    }

    /**
     * 收集配置数据
     *
     * @param mimicTypeEnum
     * @param paramMap
     * @return
     */
    private List<ConfigData> getConfigDataList(MimicTypeEnum mimicTypeEnum, Map<MimicParamKeyEnum, String> paramMap) {
        List<ConfigData> configDataList = new ArrayList<>();
        List<ConfigDataCollectSpi> configDataCollectSpiList = MimicSpiServiceFactory.getSpiService(mimicTypeEnum, ConfigDataCollectSpi.class);
        for (ConfigDataCollectSpi configDataCollectSpi : configDataCollectSpiList) {
            String msg = "配置数据收集： " + configDataCollectSpi.getClass();
            List<ConfigData> re = configDataCollectSpi.configDataCollect(paramMap);
            if (CollectionUtils.isEmpty(re)) {
                continue;
            }
            for (ConfigData configData : re) {
                if (Objects.isNull(configData)) {
                    continue;
                }
                Assert.notNull(configData.getTableName(), msg + ", tableName不能为空");
                Assert.notNull(configData.getTargetClass(), msg + ", targetClass不能为空");
                if (CollectionUtils.isEmpty(configData.getEntityList())) {
                    log.warn(msg + ", " + configData.getTableName() + ", " + configData.getTargetClass() + ", 收集数据内容为空");
                    continue;
                }
                if (configData.getEntityList().stream().anyMatch(item -> Objects.isNull(item))) {
                    throw new RuntimeException(msg + ", 收集的配置数据中包含空数据");
                }
                configDataList.add(configData);
            }
        }
        return configDataList;
    }

    /**
     * 复制配置数据
     *
     * @return
     */
    private void configDataCopy(MimicTypeEnum mimicTypeEnum, Map<MimicParamKeyEnum, String> paramMap,
        List<ConfigData> configDataList) {
        if (CollectionUtils.isEmpty(configDataList)) {
            return;
        }
        List<ConfigDataCopySpi> configDataCopySpiList = MimicSpiServiceFactory.getSpiService(mimicTypeEnum, ConfigDataCopySpi.class);
        for (ConfigData configData : configDataList) {
            for (ConfigDataCopySpi configDataCopySpi : configDataCopySpiList) {
                configDataCopySpi.configDataCopy(paramMap, configData);
            }
        }
    }

    /**
     * 复制元数据
     *
     * @return
     */
    private void metadataCopy(Map<MimicParamKeyEnum, String> paramMap, GspMetadata gspMetadata) {
        if (Objects.isNull(gspMetadata)) {
            return;
        }
        // 复制前事件
        MimicServiceEventBroker broker = SpringBeanUtils.getBean(MimicServiceEventBroker.class);
        MimicServiceEventArgs args = new MimicServiceEventArgs(gspMetadata);
        broker.fireMetadataBeforeCopyEvent(args);
        // 框架层复制处理
        metadataFrameCopy(gspMetadata);
        // 各类元数据复制处理
        MetadataCopySpi metadataCopySpi = MetadataCopyHelper.getInstance().getMetadataCopySpi(gspMetadata.getHeader().getType());
        if (Objects.nonNull(metadataCopySpi)) {
            metadataCopySpi.metadataCopy(paramMap, gspMetadata);
        }
        // 复制后事件
        broker.fireMetadataAfterCopyEvent(args);
        // 将复制后的元数据保存到上下文
        MimicServiceContextHolder.saveCopiedGspMetadata(gspMetadata);
    }

    /**
     * 框架层复制处理
     *
     * @param gspMetadata
     */
    private void metadataFrameCopy(GspMetadata gspMetadata) {
        // namespace和业务对象id赋新值
        String oldNamespace = gspMetadata.getHeader().getNameSpace();
        Assert.notNull(oldNamespace, "不符合元数据模型规则,namespace不能为空");
        String[] namespaces = oldNamespace.split(Constants.DOT_SPLIT);
        String oldBoCode = namespaces[namespaces.length - 1];
        String boIdVariable = Constants.BO_TABLE_NAME + Constants.UNDER_LINE + Constants.BO_ID + Constants.UNDER_LINE + gspMetadata.getHeader().getBizobjectID();
        String boCodeVariable = Constants.BO_TABLE_NAME + Constants.UNDER_LINE + Constants.BO_CODE + Constants.UNDER_LINE + oldBoCode;
        namespaces[namespaces.length - 1] = MimicServiceContextHolder.findConfigDataNewValue(boCodeVariable);
        gspMetadata.getHeader().setBizobjectID(MimicServiceContextHolder.findConfigDataNewValue(boIdVariable));
        gspMetadata.getHeader().setNameSpace(String.join(Constants.DOT, namespaces));
    }

    /**
     * 全局替换UUID
     *
     * @param gspMetadata
     * @return
     */
    private GspMetadata updateUUID(GspMetadata gspMetadata) {
        Optional<MimicServiceContext> mimicServiceContextOptional = MimicServiceContextHolder.getCurrentContext();
        if (!mimicServiceContextOptional.isPresent()) {
            return gspMetadata;
        }
        Map<String, String> oldUUID2NewUUIDMap = mimicServiceContextOptional.get().getOldUUID2NewUUIDMap();
        String gspMetadataStr = new MetadataSerializer().serialize(gspMetadata);
        for (Map.Entry<String, String> entry : oldUUID2NewUUIDMap.entrySet()) {
            gspMetadataStr = gspMetadataStr.replace(entry.getKey(), entry.getValue());
        }
        return new MetadataSerializer().deserialize(gspMetadataStr, GspMetadata.class);
    }

    /**
     * 复制元数据
     *
     * @return
     */
    private List<GspMetadata> metadataCopy(Map<MimicParamKeyEnum, String> paramMap,
        List<GspMetadata> gspMetadataList) {
        if (CollectionUtils.isEmpty(gspMetadataList)) {
            return null;
        }
        // 获取元数据依赖
        Map<String, List<MetadataReference>> mdId2MdRefMap = new HashMap<>();
        gspMetadataList.forEach(gspMetadata -> {
            IMetadataRtReferenceManager metadataRtReferenceManager = ReferenceHelper.getInstance().getManager(gspMetadata.getHeader().getType());
            if (Objects.nonNull(metadataRtReferenceManager)) {
                mdId2MdRefMap.put(gspMetadata.getHeader().getId(), metadataRtReferenceManager.getConstraint(gspMetadata));
            }
        });
        // 构造依赖顺序
        List<GspMetadata> orderedGspMetadataList = new ArrayList<>();
        int counter = 1;  //计数器,每次至少要处理掉一个元数据，否则退出
        while (!CollectionUtils.isEmpty(gspMetadataList)) {
            if (counter == 0) {
                gspMetadataList.forEach(gspMetadata -> log.error(gspMetadata.toString()));
                throw new RuntimeException("无法构造元数据依赖关系, 具体错误详情请查看系统日志");
            }
            counter = 0;
            Iterator<GspMetadata> iterator = gspMetadataList.iterator();
            while (iterator.hasNext()) {
                GspMetadata gspMetadata = iterator.next();
                if (isTargetGspMetadata(gspMetadata, gspMetadataList, mdId2MdRefMap)) {
                    orderedGspMetadataList.add(gspMetadata);
                    iterator.remove();
                    counter++;
                }
            }
        }
        // 按依赖顺序处理元数据
        orderedGspMetadataList.forEach(gspMetadata -> {
            metadataCopy(paramMap, gspMetadata);
        });
        List<GspMetadata> result = new ArrayList<>();
        // 元数据框架层做UUID统一替换
        orderedGspMetadataList.forEach(gspMetadata -> {
            GspMetadata gspMetadataForUpdate = updateUUID(gspMetadata);
            if (Objects.nonNull(gspMetadataForUpdate)) {
                result.add(gspMetadataForUpdate);
            }
        });
        return result;
    }

    /**
     * 检查是否叶子节点
     *
     * @param gspMetadata
     * @param gspMetadataList
     * @param mdId2MdRefMap
     * @return
     */
    private boolean isTargetGspMetadata(GspMetadata gspMetadata, List<GspMetadata> gspMetadataList,
        Map<String, List<MetadataReference>> mdId2MdRefMap) {
        List<MetadataReference> metadataReferenceList = mdId2MdRefMap.get(gspMetadata.getHeader().getId());
        // 不存在引用关系,则属于复制目标
        if (CollectionUtils.isEmpty(metadataReferenceList)) {
            return true;
        }
        // 存在引用关系，且引用的元数据在当前应用中，则不符合复制目标
        Set<String> mdIdSet = gspMetadataList.stream().map(gspMetadata1 -> gspMetadata1.getHeader().getId()).collect(Collectors.toSet());
        for (MetadataReference metadataReference : metadataReferenceList) {
            if (mdIdSet.contains(metadataReference.getDependentMetadata().getId())) {
                return false;
            }
        }
        return true;
    }

    /**
     * 获取运行时服务
     *
     * @return
     */
    private CustomizationService getCustomizationService() {
        if (Objects.isNull(customizationService)) {
            customizationService = SpringBeanUtils.getBean(CustomizationService.class);
        }
        return customizationService;
    }

    /**
     * 获取复制保存服务
     *
     * @return
     */
    private MimicSaveService getMimicSaveService() {
        if (Objects.isNull(mimicSaveService)) {
            mimicSaveService = SpringBeanUtils.getBean(MimicSaveService.class);
        }
        return mimicSaveService;
    }

    /**
     * 解析模板数据
     *
     * @param appTemplateDto
     * @return
     */
    private AppTemplate convertToAppTemplate(AppTemplateDto appTemplateDto) {
        List<GspMetadata> gspMetadataList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(appTemplateDto.getGspMetadataJsonList())) {
            for (String gspMetadataStr : appTemplateDto.getGspMetadataJsonList()) {
                gspMetadataList.add(new MetadataSerializer().deserialize(gspMetadataStr, GspMetadata.class));
            }
        }
        List<ConfigData> configDataList = new ArrayList<>();
        ObjectMapper objectMapper = ServiceUtils.getMapper();
        objectMapper.registerModule(new JavaTimeModule());
        try {
            if (!CollectionUtils.isEmpty(appTemplateDto.getConfigDataJsonList())) {
                for (String configDataStr : appTemplateDto.getConfigDataJsonList()) {
                    ConfigData configData = objectMapper.readValue(configDataStr, ConfigData.class);
                    configData.setEntityList(objectMapper.readValue(objectMapper.readTree(configDataStr).findValue("EntityList").toString(), objectMapper.getTypeFactory().constructCollectionType(List.class, Class.forName(configData.getTargetClass()))));
                    configDataList.add(configData);
                }
            }
        } catch (Exception e) {
            log.error("配置数据反序列化发生异常:{}", e);
            throw new RuntimeException("配置数据反序列化发生异常:{}", e);
        }
        AppTemplate appTemplate = new AppTemplate();
        appTemplate.setGspMetadataList(gspMetadataList);
        appTemplate.setConfigDataList(configDataList);
        return appTemplate;
    }

    /**
     * 转换为模板数据
     *
     * @return
     */
    private AppTemplateDto convertToAppTemplateDto(MimicTypeEnum mimicTypeEnum, List<GspMetadata> gspMetadataList,
        List<ConfigData> configDataList) {
        ObjectMapper objectMapper = ServiceUtils.getMapper();
        objectMapper.registerModule(new JavaTimeModule());
        List<String> gspMetadataStrList = new ArrayList<>();
        for (GspMetadata gspMetadata : gspMetadataList) {
            gspMetadataStrList.add(new MetadataSerializer().serialize(gspMetadata));
        }
        List<String> configDataStrList = new ArrayList<>();
        try {
            for (ConfigData configData : configDataList) {
                configDataStrList.add(objectMapper.writeValueAsString(configData));
            }
        } catch (Exception e) {
            log.error("配置数据序列化发生异常:{}", e);
            throw new RuntimeException("配置数据序列化发生异常:{}", e);
        }
        AppTemplateDto appTemplateDto = new AppTemplateDto();
        appTemplateDto.setGspMetadataJsonList(gspMetadataStrList);
        appTemplateDto.setConfigDataJsonList(configDataStrList);
        appTemplateDto.setMimicType(mimicTypeEnum.getCode());
        return appTemplateDto;
    }

    /**
     * 获取配置数据前置处理顺序
     *
     * @return
     */
    private List<ConfigData> getPreConfigData(List<ConfigData> configDataList) {
        if (CollectionUtils.isEmpty(configDataList)) {
            return null;
        }
        // 读取配置信息
        List<ConfigDataConfiguration> configDataPreConfigurationList;
        try {
            configDataPreConfigurationList = MetadataServiceHelper.getConfigurationList(ServiceUtils.getAbsoluteConfigFilePath(CustomizationConfigLoader.fileName), CONFIG_DATA_PRE_CONFIGURATION, ConfigDataConfiguration.class);
        } catch (Exception e) {
            throw new RuntimeException("读取配置失败: " + CONFIG_DATA_PRE_CONFIGURATION, e);
        }
        // 获取激活的配置项并进行排序
        if (CollectionUtils.isEmpty(configDataPreConfigurationList)) {
            return null;
        }
        configDataPreConfigurationList = configDataPreConfigurationList.stream()
            .filter(configuration -> configuration.getActive())
            .filter(configuration -> Objects.nonNull(configuration.getTableName()))
            .sorted(Comparator.comparing(ConfigDataConfiguration::getOrder))
            .collect(Collectors.toList());
        // 获取前置处理数据
        List<ConfigData> preConfigDataList = new ArrayList<>();
        for (ConfigDataConfiguration configDataConfiguration : configDataPreConfigurationList) {
            Iterator<ConfigData> iterator = configDataList.iterator();
            while (iterator.hasNext()) {
                ConfigData configData = iterator.next();
                if (configDataConfiguration.getTableName().equalsIgnoreCase(configData.getTableName())) {
                    preConfigDataList.add(configData);
                    iterator.remove();
                }
            }
        }
        return preConfigDataList;
    }

    /**
     * 获取配置数据后置处理顺序
     *
     * @return
     */
    private List<ConfigData> getPostConfigData(List<ConfigData> configDataList) {
        if (CollectionUtils.isEmpty(configDataList)) {
            return null;
        }
        // 读取配置信息
        List<ConfigDataConfiguration> configDataPostConfigurationList;
        try {
            configDataPostConfigurationList = MetadataServiceHelper.getConfigurationList(ServiceUtils.getAbsoluteConfigFilePath(CustomizationConfigLoader.fileName), CONFIG_DATA_POST_CONFIGURATION, ConfigDataConfiguration.class);
        } catch (Exception e) {
            throw new RuntimeException("读取配置失败: " + CONFIG_DATA_POST_CONFIGURATION, e);
        }
        // 获取激活的配置项并进行排序
        if (CollectionUtils.isEmpty(configDataPostConfigurationList)) {
            return configDataList;
        }
        configDataPostConfigurationList = configDataPostConfigurationList.stream()
            .filter(configuration -> configuration.getActive())
            .filter(configuration -> Objects.nonNull(configuration.getTableName()))
            .sorted(Comparator.comparing(ConfigDataConfiguration::getOrder))
            .collect(Collectors.toList());
        // 获取后置处理数据
        List<ConfigData> postConfigDataList = new ArrayList<>();
        for (ConfigDataConfiguration configDataConfiguration : configDataPostConfigurationList) {
            Iterator<ConfigData> iterator = configDataList.iterator();
            while (iterator.hasNext()) {
                ConfigData configData = iterator.next();
                if (configDataConfiguration.getTableName().equalsIgnoreCase(configData.getTableName())) {
                    postConfigDataList.add(configData);
                    iterator.remove();
                }
            }
        }
        postConfigDataList.addAll(configDataList);
        return postConfigDataList;
    }

    /**
     * 提取配置数据
     *
     * @param gspMetadataList
     */
    private void extractConfigData(List<GspMetadata> gspMetadataList) {
        if (CollectionUtils.isEmpty(gspMetadataList)) {
            return;
        }
        for (GspMetadata gspMetadata : gspMetadataList) {
            // 各类元数据复制处理
            ExtractConfigDataSpi extractConfigDataSpi = ExtractConfigDataHelper.getInstance().getExtractConfigDataSpi(gspMetadata.getHeader().getType());
            if (Objects.nonNull(extractConfigDataSpi)) {
                MimicServiceContextHolder.saveConfigDataDependencies(extractConfigDataSpi.extractConfigDataDependencies(gspMetadata));
            }
        }
    }

    /**
     * 生成新元数据id
     *
     * @param gspMetadataList
     */
    private void generateMdId(List<GspMetadata> gspMetadataList) {
        if (CollectionUtils.isEmpty(gspMetadataList)) {
            return;
        }
        for (GspMetadata gspMetadata : gspMetadataList) {
            MimicServiceContextHolder.saveUUID(gspMetadata.getHeader().getId(), UUID.randomUUID().toString());
        }
    }
}
